package scm;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.sql.*;

public class RegWindow extends JFrame
{
    private JLabel jLabel1, jLabel2, jLabel3, jLabel4, jLabel5, jLabel6, jLabel7, jLabel8, jLabel9;
    private JTextField jTextField1, jTextField2, jTextField3, jTextField4, jTextField6;
    private JFormattedTextField jTextField7,jTextField5;
    private JPasswordField jPasswordField1;
    private JComboBox jcmb;
    private JButton jButton1;
    private JPanel contentPane;
    private Connection c = null;

    public RegWindow()
    {
        super();
	create();
        this.setVisible(true);
    }


    private void create()
    {
        jLabel1 = new JLabel();
	jLabel2 = new JLabel();
        jLabel3 = new JLabel();
	jLabel4 = new JLabel();
        jLabel5 = new JLabel();
	jLabel6 = new JLabel();
        jLabel7 = new JLabel();
	jLabel8 = new JLabel();
        jLabel9 = new JLabel();
	jTextField1 = new JTextField();
        jTextField2 = new JTextField();
        jTextField3 = new JTextField();
        jTextField4 = new JTextField();
        jTextField6 = new JTextField();
        jTextField5 = new JFormattedTextField(createFormatter("##-###"));
        jTextField7 = new JFormattedTextField(createFormatter("####-##-##"));
        jcmb = new JComboBox();
        jcmb.setModel(new DefaultComboBoxModel(new String[] {"Rozsylacz", "Obserwator", "Administrator"}));

	jPasswordField1 = new JPasswordField();
	jButton1 = new JButton();
	contentPane = (JPanel)this.getContentPane();

	jLabel1.setHorizontalAlignment(SwingConstants.LEFT);
	jLabel1.setForeground(new Color(0, 0, 255));
	jLabel1.setText("Login:");

	jLabel2.setHorizontalAlignment(SwingConstants.LEFT);
	jLabel2.setForeground(new Color(0, 0, 255));
	jLabel2.setText("Hasło:");

        jLabel3.setHorizontalAlignment(SwingConstants.LEFT);
	jLabel3.setForeground(new Color(0, 0, 255));
	jLabel3.setText("E-mail:");

        jLabel4.setHorizontalAlignment(SwingConstants.LEFT);
	jLabel4.setForeground(new Color(0, 0, 255));
	jLabel4.setText("Imię:");

        jLabel5.setHorizontalAlignment(SwingConstants.LEFT);
	jLabel5.setForeground(new Color(0, 0, 255));
	jLabel5.setText("Nazwisko:");

        jLabel9.setHorizontalAlignment(SwingConstants.LEFT);
	jLabel9.setForeground(new Color(0, 0, 255));
	jLabel9.setText("Stanowisko:");

        jTextField1.setForeground(new Color(0, 0, 255));
	jTextField1.setSelectedTextColor(new Color(0, 0, 255));
	jTextField1.setToolTipText("Podaj nazwę użytkownika");

	jPasswordField1.setForeground(new Color(0, 0, 255));
	jPasswordField1.setToolTipText("Podaj hasło");

        jTextField2.setForeground(new Color(0, 0, 255));
	jTextField2.setSelectedTextColor(new Color(0, 0, 255));
	jTextField2.setToolTipText("Podaj e-mail");

        jTextField3.setForeground(new Color(0, 0, 255));
	jTextField3.setSelectedTextColor(new Color(0, 0, 255));
	jTextField3.setToolTipText("Podaj imię");

        jTextField4.setForeground(new Color(0, 0, 255));
	jTextField4.setSelectedTextColor(new Color(0, 0, 255));
	jTextField4.setToolTipText("Podaj nazwisko");

        JPanel pane = new JPanel(new GridLayout(6,2));
        pane.add(jLabel1);
        pane.add(jTextField1);
        pane.add(jLabel2);
        pane.add(jPasswordField1);
        pane.add(jLabel3);
        pane.add(jTextField2);
        pane.add(jLabel4);
        pane.add(jTextField3);
        pane.add(jLabel5);
        pane.add(jTextField4);
        pane.add(jLabel9);
        pane.add(jcmb);
        pane.setSize(new Dimension(100, 100));
        pane.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createTitledBorder("Pola obowiązkowe"),
                        BorderFactory.createEmptyBorder(5,5,5,5)));

        jLabel6.setHorizontalAlignment(SwingConstants.LEFT);
	jLabel6.setForeground(new Color(0, 0, 255));
	jLabel6.setText("Miejscowość:");

        jLabel7.setHorizontalAlignment(SwingConstants.LEFT);
	jLabel7.setForeground(new Color(0, 0, 255));
	jLabel7.setText("Kod pocztowy:");

        jLabel8.setHorizontalAlignment(SwingConstants.LEFT);
	jLabel8.setForeground(new Color(0, 0, 255));
	jLabel8.setText("Data urodzenia (RRRR-MM-DD):");

        jTextField6.setForeground(new Color(0, 0, 255));
	jTextField6.setSelectedTextColor(new Color(0, 0, 255));
	jTextField6.setToolTipText("Podaj miejscowość");

        jTextField5.setForeground(new Color(0, 0, 255));
	jTextField5.setSelectedTextColor(new Color(0, 0, 255));
	jTextField5.setToolTipText("Podaj kod pocztowy");

        jTextField7.setForeground(new Color(0, 0, 255));
	jTextField7.setSelectedTextColor(new Color(0, 0, 255));
	jTextField7.setToolTipText("Podaj datę urodzenia");

        JPanel pane2 = new JPanel(new GridLayout(3,2));
        pane2.setSize(200, 200);
        pane2.add(jLabel6);
        pane2.add(jTextField6);
        pane2.add(jLabel7);
        pane2.add(jTextField5);
        pane2.add(jLabel8);
        pane2.add(jTextField7);
        pane2.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createTitledBorder("Pola opcjonalne"),
                        BorderFactory.createEmptyBorder(5,5,5,5)));

	jButton1.setBackground(new Color(204, 204, 204));
	jButton1.setForeground(new Color(0, 0, 255));
	jButton1.setText("Rejestruj");
	jButton1.addActionListener(new ActionListener()
        {
	    public void actionPerformed(ActionEvent e)
	    {
		jButton1_actionPerformed(e);
	    }

	});

	contentPane.setLayout(null);
	contentPane.setBackground(new Color(204, 204, 204));
	addComponent(contentPane, pane, 2,2,620,178);
        addComponent(contentPane, pane2, 2,181,620,120);
        addComponent(contentPane, jButton1, 250,302,103,38);

	this.setTitle("Rejestracja");
	this.setLocation(new Point(250,250));
	this.setSize(new Dimension(635, 380));
	this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	this.setResizable(false);
    }

    protected MaskFormatter createFormatter(String s)
    {
        MaskFormatter formatter = null;
        try
        {
            formatter = new MaskFormatter(s);
        }
        catch (java.text.ParseException exc)
        {
            System.err.println("Niepoprawny formater: " + exc.getMessage());
            System.exit(-1);
        }
        return formatter;
    }


    private void addComponent(Container container,Component c,int x,int y,int width,int height)
    {
	c.setBounds(x,y,width,height);
	container.add(c);
    }


    private void jButton1_actionPerformed(ActionEvent e)
    {
        String username = new String(jTextField1.getText());
	String password = new String(jPasswordField1.getText());
        String email = new String(jTextField2.getText());
        String imie = new String(jTextField3.getText());
        String nazwisko = new String(jTextField4.getText());
        String miejscowosc = new String(jTextField6.getText());
        String kod = new String(jTextField5.getText());
        String stan = new String((String) jcmb.getSelectedItem());
        String data = new String(jTextField7.getText());

        EmailValidator ev = new EmailValidator(email);

	if(username.equals("") || password.equals("") || email.equals("") || imie.equals("") || nazwisko.equals(""))
	{
	    jButton1.setEnabled(false);
	    JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>Musisz wypełnić wymagane pola.</FONT></HTML>");
	    JOptionPane.showMessageDialog(null,errorFields);
	    jButton1.setEnabled(true);
	    this.setVisible(true);
	}
        else if (password.length() < 6)
        {
            jButton1.setEnabled(false);
	    JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>Hasło musi mieć co najmniej 6 znaków.</FONT></HTML>");
	    JOptionPane.showMessageDialog(null,errorFields);
	    jButton1.setEnabled(true);
	    this.setVisible(true);
        }
        else if (!ev.check())
        {
            jButton1.setEnabled(false);
	    JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>Format adresu e-mail jest niepoprawny.</FONT></HTML>");
	    JOptionPane.showMessageDialog(null,errorFields);
	    jButton1.setEnabled(true);
	    this.setVisible(true);
        }
        else
        {
             try
             {
                 Class.forName("org.postgresql.Driver");
             }
             catch (ClassNotFoundException cnfe)
             {
                 JOptionPane.showMessageDialog(null, cnfe.getMessage());
             }
             try
             {
                 c = DriverManager.getConnection("jdbc:postgresql://localhost/template1",
                                    "postgres", "przemek");

                 PreparedStatement ps = c.prepareStatement("INSERT INTO users (login, password) VALUES(? , ?)");
                 ps.setString(1, username);
                 ps.setString(2, password);
                 int rows_affected = ps.executeUpdate();

                 PreparedStatement ps2 = c.prepareStatement("SELECT id FROM users WHERE login = ?");
                 ps2.setString(1, username);
                 ResultSet rs = ps2.executeQuery();

                 String id = "0";


                 while (rs.next())
                 {
                      id = rs.getString("id");
                 }

                 boolean isDate = true, isKod = true;
                 
                 try
                 {
                     java.sql.Date.valueOf(data);
                 }
                 catch (IllegalArgumentException ex)
                 {
                     isDate = false;
                 }

                 try
                 {
                     Integer.parseInt(String.valueOf(kod.charAt(0)));
                 }
                 catch (IllegalArgumentException ex)
                 {
                     isKod = false;
                 }

                 if (isDate && isKod)
                 {
                    PreparedStatement ps3 = c.prepareStatement("INSERT INTO userdata VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
                    ps3.setInt(1, Integer.parseInt(id));
                    ps3.setString(2, imie);
                    ps3.setString(3, nazwisko);
                    ps3.setString(4, miejscowosc);
                    ps3.setString(5, kod);
                    ps3.setString(6, email);
                    ps3.setDate(7, java.sql.Date.valueOf(data));
                    ps3.setString(8, stan);
                    rows_affected = ps3.executeUpdate();
                 }
                 else if (!isDate && isKod)
                 {
                     PreparedStatement ps3 = c.prepareStatement("INSERT INTO userdata(id, forename, surname, city, post_code, e_mail, position) VALUES(?, ?, ?, ?, ?, ?, ?)");
                     ps3.setInt(1, Integer.parseInt(id));
                     ps3.setString(2, imie);
                     ps3.setString(3, nazwisko);
                     ps3.setString(4, miejscowosc);
                     ps3.setString(5, kod);
                     ps3.setString(6, email);
                     ps3.setString(7, stan);
                     rows_affected = ps3.executeUpdate();
                 }
                 else if (!isDate && !isKod)
                 {
                     PreparedStatement ps3 = c.prepareStatement("INSERT INTO userdata(id, forename, surname, city, e_mail, position) VALUES(?, ?, ?, ?, ?, ?)");
                     ps3.setInt(1, Integer.parseInt(id));
                     ps3.setString(2, imie);
                     ps3.setString(3, nazwisko);
                     ps3.setString(4, miejscowosc);
                     ps3.setString(5, email);
                     ps3.setString(6, stan);
                     rows_affected = ps3.executeUpdate();
                 }
                 else if (isDate && !isKod)
                 {
                     PreparedStatement ps3 = c.prepareStatement("INSERT INTO userdata(id, forename, surname, city, e_mail, birth, position) VALUES(?, ?, ?, ?, ?, ?, ?)");
                     ps3.setInt(1, Integer.parseInt(id));
                     ps3.setString(2, imie);
                     ps3.setString(3, nazwisko);
                     ps3.setString(4, miejscowosc);
                     ps3.setString(5, email);
                     ps3.setDate(6, java.sql.Date.valueOf(data));
                     ps3.setString(7, stan);
                     rows_affected = ps3.executeUpdate();
                 }

                 if (rows_affected == 0)
                 {
                     jButton1.setEnabled(false);
	             JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>Rejestracja nieudana, wprowadź dane jeszcze raz.</FONT></HTML>");
	             JOptionPane.showMessageDialog(null,errorFields);
	             jButton1.setEnabled(true);
	             this.setVisible(true);
                 }
                 else
                 {
                     JOptionPane.showMessageDialog(null, "Rejestracja się powiodła.");
                     this.dispose();
                 }



             }
             catch (SQLException se)
             {
                 JOptionPane.showMessageDialog(null, se.getMessage());
             }
        }
    }
}
